<template>
	<el-dialog
		width="1000px"
		:visible.sync="show"
		:close-on-click-modal="false"
		:before-close="handleClose"
		top="3vh"
	>
		<template #title>
			<div class="rp-header">
				<h3 class="dialog-title">重复试题处理</h3>
				<el-button
					@click="handleSave"
					type="primary"
					size="mini"
					class="rp-save"
					style="position: absolute"
					:loading="isSaving"
				>
					完成
				</el-button>
			</div>
		</template>
		<p class="rp-tip">
			<strong>已处理：<span class="rp-tip-process">{{ Process }}</span> 题  未处理：<span class="rp-tip-not">{{ unProcess }}</span> 题</strong>&ensp;
			<el-dropdown @command="handleOneCommand">
				<el-button type="primary">
					一键去重<i class="el-icon-arrow-down el-icon--right" />
				</el-button>
				<el-dropdown-menu slot="dropdown">
					<el-dropdown-item command="abandon">全部放弃添加</el-dropdown-item>
					<el-dropdown-item command="updateBase">
						全部更新已有试题基本信息
						<el-tooltip
							class="item"
							effect="dark"
							placement="bottom"
						>
							<ul slot="content" class="update-tip">
								<li>以下新增试题将覆盖已有重复试题，但不影响已有试题的组卷记录和做题记录</li>
								<li>仅更新试题基本信息（题干、选项、答案、解析）</li>
							</ul>
							<i class="el-icon-question" />
						</el-tooltip>
					</el-dropdown-item>
					<el-dropdown-item command="update">
						全部更新已有试题全部信息
						<el-tooltip
							class="item"
							effect="dark"
							placement="bottom"
						>
							<ul slot="content" class="update-tip">
								<li>以下新增试题将覆盖已有重复试题，但不影响已有试题的组卷记录和做题记录</li>
								<li>更新试题全部信息（题干、选项、答案、解析、章节、知识点、标签信息）</li>
							</ul>
							<i class="el-icon-question" />
						</el-tooltip>
					</el-dropdown-item>
				</el-dropdown-menu>
			</el-dropdown>
		</p>
		<el-container style="margin-top: 20px">
			<el-aside style="width: 250px;max-height: 80vh;overflow: auto;background-color: white;">
				<ul>
					<li v-for="(item, index) in dataList" :key="item.id">
						<p class="ques-type-title">
							<b>{{ chnNumbers[index + 1] }}、{{ item.questionTypeName }}</b>
							&ensp;
							<span class="ques-count">({{ item.questionTypeDataList.length }}题)</span>
						</p>
						<ul class="question-list">
							<li
								v-for="qitem in item.questionTypeDataList"
								:key="qitem.resourceId"
								class="question-item"
								:class="{
									'question-item-process': qitem.isProcess,
									'question-item-checked': qitem.isChecked,
								}"
								@click="handleQuestionClick(qitem)"
							>
								{{ qitem.questionSeq }}
							</li>
						</ul>
					</li>
				</ul>
			</el-aside>
			<div class="rl-main-line" />
			<el-main style="padding-top: 0" class="rpd-content">
				<p class="rp-question-detail-add">
					<b>本次新增试题</b>&ensp;

					<!-- <el-button class="theme_font_color theme-border-color" size="mini" @click="download">下载模板</el-button> -->
					<el-button
						class="theme_font_color theme-border-color rpd-btn"
						size="mini"
						@click="handleAbandon"
						:disabled="hasChecked"
						:style="{
							borderColor: currentAddQues && currentAddQues.opType === 'abandon' ? 'green !important' : 'inherit',
						}"
						ref="btnCancel"
					>
						放弃添加
					</el-button>
					<el-button
						class="theme_font_color theme-border-color rpd-btn"
						size="mini"
						@click="handleUpdateBase"
						:disabled="hasChecked"
						:style="{
							borderColor: currentAddQues && currentAddQues.opType === 'base' ? 'green !important' : 'inherit',
						}"
						ref="btnUpdateBase"
					>
						更新已有试题基本信息
					</el-button>						
					<el-tooltip
						class="item"
						effect="dark"
						placement="bottom"
					>
						<ul slot="content" class="update-tip">
							<li>本次新增试题将覆盖已有重复试题，但不影响已有试题的组卷记录和做题记录</li>
							<li>仅更新试题基本信息（题干、选项、答案、解析）</li>
						</ul>
						<i class="el-icon-question" />
					</el-tooltip>
					<el-button
						class="theme_font_color theme-border-color rpd-btn"
						size="mini"
						@click="handleUpdate"
						:disabled="hasChecked"
						:style="{
							borderColor: currentAddQues && currentAddQues.opType === 'all' ? 'green !important' : 'inherit',
						}"
						ref="btnUpdate"
					>
						更新已有试题全部信息
					</el-button>						
					<el-tooltip
						class="item"
						effect="dark"
						placement="bottom"
					>
						<ul slot="content" class="update-tip">
							<li>本次新增试题将覆盖已有重复试题，但不影响已有试题的组卷记录和做题记录</li>
							<li>更新试题全部信息（题干、选项、答案、解析、章节、知识点、标签信息）</li>
						</ul>
						<i class="el-icon-question" />
					</el-tooltip>
				</p>
				<div class="question-add-wrapper">
					<question-show
						v-if="currentAddQues"
						:data="currentAddQues"
					/>
				</div>
				<p class="rp-question-detail-repeat"><b>已有重复试题</b></p>
				<div class="question-repeat-wrapper" v-loading="isLoading">
					<question-show
						v-if="currentUpdateQues"
						:data="currentUpdateQues"
					/>
				</div>
			</el-main>
		</el-container>
	</el-dialog>
</template>
<script>
	import QuestionShow from '@rc/pages/components/question-base/question-show/index.vue';
	import questionApi from "@rc/apis/rc/question.mjs";

	export default {
		components:{
        	QuestionShow
    	},
		props: {
			// 弹窗显示
			show: {
				type: Boolean,
				default: false
			},
			isSaving: {
				type: Boolean,
				default: false
			},
			dataList: {
				type: Array,
				default: () => ([])
			},
		},
		/**
		 * 数据模型
		 * 
		 * @returns {object} return 数据模型
		 */
		data() {
			return {
				chnNumbers: {
					'1': '一',
					'2': '二',
					'3': '三',
					'4': '四',
					'5': '五',
					'6': '六',
					'7': '七',
					'8': '八',
					'9': '九',
					'10': '十',
					'11': '一十一',
					'12': '一十二',
					'13': '一十三',
					'14': '一十四',
					'15': '一十五',
					'16': '一十六',
					'17': '一十七',
					'18': '一十八',
					'19': '一十九',
					'20': '二十',
				},
				questionOnlineCache: null,
				isLoading: false,
			};
		},
		computed: {
			/**
			 * 试题列表
			 * 
			 * @returns {Array} ret 试题列表
			 */
			questionList() {
				return this.dataList.flatMap(({ questionTypeDataList }) => questionTypeDataList);
			},
			/**
			 * 未处理数量
			 * 
			 * @returns {number} ret 数量
			 */
			unProcess() {
				return this.questionList.reduce((pre, curr) => pre + Number(curr.isProcess === false), 0);
			},
			/**
			 * 处理数量
			 * 
			 * @returns {number} ret 数量
			 */
			Process() {
				return this.questionList.reduce((pre, curr) => pre + Number(curr.isProcess), 0);
			},
			/**
			 * 当前选中的试题
			 * 
			 * @returns {object} ret 试题
			 */
			currentAddQues() {
				return this.questionList.find(({ isChecked }) => isChecked);
			},
			/**
			 * 当前选中的试题
			 * 
			 * @returns {object} ret 试题
			 */
			 currentUpdateQues() {
				if (!this.currentAddQues) {
					return;
				}
				return this.questionOnlineCache[this.currentAddQues.repeatResourceId];
			},
			/**
			 * 是否选中
			 * 
			 * @returns {boolean} ret 是否选中
			 */
			 hasChecked() {
				return this.questionList.length > 0 && this.questionList.every(({ isChecked }) => isChecked === false);
			},
		},
		watch: {
			/**
			 * 监听显示状态
			 * 	 
			 * @param {boolean} val 是否显示
			 */
			show(val) {
				if (val) {
					// this.handleDataInit();
				} else {
					this.questionList.forEach((item) => {
						delete item.isShowChapter;
						delete item.isShowKnowledge;
						delete item.isShowLabel;
						delete item.isProcess;
						delete item.isChecked;
						delete item.opType;
						if (item.smallQuestionList) {
							item.smallQuestionList.forEach((citem) => {
								delete citem.isShowChapter;
								delete citem.isShowKnowledge;
								delete citem.isShowLabel;
							});
						}
					});

					const dmas = document.querySelectorAll('.rpd-content audio');
					dmas.forEach((dms) => {
						dms.pause();
					});
					const dmvs = document.querySelectorAll('.rpd-content video');
					dmvs.forEach((dms) => {
						dms.pause();
					});
				}
			},
			/**
			 * 数据变动列表
			 */
			dataList() {
				if (this.show === true) {
					this.handleDataInit();
				}
			},
		},
        methods: {
			/**
			 * 初始数据
			 */
			handleDataInit() {
				const c = {};
				this.questionList.forEach((item) => {
					c[item.repeatResourceId] = 0;
					this.$set(item, 'isShowChapter', true);
					this.$set(item, 'isShowKnowledge', true);
					this.$set(item, 'isShowLabel', true);
					this.$set(item, 'isProcess', false);
					this.$set(item, 'isChecked', false);
					this.$set(item, 'opType', '');
					if (item.smallQuestionList) {
						item.smallQuestionList.forEach((citem) => {
							this.$set(citem, 'isShowChapter', true);
							this.$set(citem, 'isShowKnowledge', true);
							this.$set(citem, 'isShowLabel', true);
						});
					}
				});
				this.questionOnlineCache = c;
				this.handleQuestionClick(this.questionList[0]);
			},
            /**
             * 返回
             */
			handleClose(){
               this.$emit("update:show", false);
            },
			/**
			 * 处理完成
			 */
			handleSave() {
				if (this.unProcess > 0) {
					this.$message({
						message: '重复试题未处理完成',
						type: 'warning'
					});
				} else {
					const abandonList = this.questionList.filter(({ opType }) => opType === 'abandon').map((item) => item);
					const updateList = this.questionList.filter(({ opType }) => opType === 'all').map((item) => item);
					const updateBaseList = this.questionList.filter(({ opType }) => opType === 'base').map((item) => item);
					this.$emit('success', { abandonList, updateList, updateBaseList });
				}
			},
			/**
			 * 一建去重
			 * 
			 * @param {string} e 类型
			 */
			handleOneCommand(e) {
				console.warn(e);
				if (e === 'abandon') {
					this.$confirm('确定本次新增的以下试题都要放弃添加吗？', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						this.questionList.forEach((item) => {
							item.isProcess = true;
							item.opType = 'abandon';
						});
					}).catch(() => {});
				} else if (e === 'update') {
					this.$confirm('确定本次新增的以下试题都要更新覆盖已有重复试题的全部信息吗？', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						this.questionList.forEach((item) => {
							item.isProcess = true;
							item.opType = 'all';
						});
					}).catch(() => {       
					});
				} else if (e === 'updateBase') {
					this.$confirm('确定本次新增的以下试题都要更新覆盖已有重复试题的基本信息吗？', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						this.questionList.forEach((item) => {
							item.isProcess = true;
							item.opType = 'base';
						});
					}).catch(() => {       
					});
				}
			},
			/**
			 * 放弃添加
			 */
			handleAbandon() {
				this.currentAddQues.isProcess = true;
				this.currentAddQues.opType = 'abandon';

				this.toNext();
			},
			/**
			 * 更新已有试题
			 */
			handleUpdate() {
				this.currentAddQues.isProcess = true;
				this.currentAddQues.opType = 'all';

				this.toNext();
			},
			/**
			 * 更新已有试题
			 */
			handleUpdateBase() {
				this.currentAddQues.isProcess = true;
				this.currentAddQues.opType = 'base';

				this.toNext();
			},
			/**
			 * 下一题
			 */
			 toNext() {
				const idx = this.questionList.findIndex((item) => item === this.currentAddQues);
				if (idx >= 0 && idx < this.questionList.length - 1) {
					this.currentAddQues.isChecked = false;
					this.handleQuestionClick(this.questionList[idx + 1]);
				}

				this.$nextTick(() => {
					// this.$refs.btnCancel.$el.blur();
					// this.$refs.btnUpdateBase.$el.blur();
					// this.$refs.btnUpdate.$el.blur();
				});
			},
			/**
			 * 点击处理
			 *
			 * @param {object} row 试题
			 */
			handleQuestionClick(row) {
				this.questionList.forEach((item) => item.isChecked = item === row);
				this.isLoading = true;
				questionApi.queryQuestionInfoV({
					resourceId: row.repeatResourceId
				}).then((resource) => {
					resource.chapterList = resource.chapterNames ? resource.chapterNames.map((item) => {
						return { chapterName: item };
					}) : [];
					resource.isShowChapter = true;
					resource.isShowKnowledge = true;
					resource.isShowLabel = true;
					if (resource.smallQuestionList) {
						resource.smallQuestionList = resource.smallQuestionList.filter(({ isAvailable }) => isAvailable === 'Y');
						resource.smallQuestionList.forEach((citem) => {
							citem.isShowChapter = true;
							citem.isShowKnowledge = true;
							citem.isShowLabel = true;
							citem.chapterList = citem.chapterNames ? citem.chapterNames.map((item) => {
								return { chapterName: item };
							}) : [];
						});
					}
					this.questionOnlineCache[row.repeatResourceId] = resource;
				}).finally(() => {
					this.isLoading = false;
				});
			},
        }
	};
</script>
<style scoped lang="less">
	/deep/ .el-dialog__body {
		padding: 10px 20px;
	}
	.dialog-title {
		text-align: center;
		font-size: 16px;
		color: #333;
	}
	.rp-header {
		position: relative;
	}
	.rp-save {
		position: absolute;
		top: 15px;
		right: 50px;
	}
	.rp-tip {
		color: #333;
		.rp-tip-not {
			color: red;
		}
		.rp-tip-process {
			color: green;
		}
	}
	.rp-question-detail-add {
		color: #333;
	}
	.rp-question-detail-repeat {
		color: #333;
	}
	.ques-type-title {
		color: #333;
		.ques-count {
			color: #9f9f9f;
			font-size: 12px;
		}
	}
	.question-list {
		margin-top: 20px;
		margin-bottom: 20px;
		display: flex;
		flex-wrap: wrap;
		.question-item {
			cursor: pointer;
			width: 32px;
			height: 32px;
			border-radius: 50%;
			display: inline-flex;
			justify-content: center;
			align-items: center;
			border: 1px solid lightgray;
			background-color: #f4f5f9;
		}

		.question-item:nth-child(n + 6) {
			margin-top: 15px;
		}

		.question-item:nth-child(5n+2),
		.question-item:nth-child(5n+3),
		.question-item:nth-child(5n+4),
		.question-item:nth-child(5n+5) {
			margin-left: 15px;
		}

		.question-item-checked {
			color: #fa837d;
			background-color: #fef5f5;
			border: 1px solid #fa837d;
		}

		.question-item-process {
			color: white;
			background-color: green;
			border: none;
		}
	}

	.rl-main-line {
		background-color: #ececec;
		width: 1px;
	}
	.question-add-wrapper {
		border: rgba(215, 215, 215, 1) 1px solid;
		min-height: 300px;
		margin-bottom: 15px;
		margin-top: 15px;
		padding: 15px;
		max-height: 30vh;
    	overflow: auto;
	}

	.question-repeat-wrapper {
		border: rgba(215, 215, 215, 1) 1px solid;
		min-height: 300px;
		margin-bottom: 15px;
		margin-top: 15px;
		padding: 15px;
		max-height: 30vh;
    	overflow: auto;
	}
	.update-tip {
		list-style-type: decimal;
		padding-left: 10px;
	}
	.rpd-btn:hover{
		background-color: white !important;
	}
	.rpd-btn:focus{
		background-color: white !important;
	}
</style>
